<template>
  <el-dialog
    :title="!dataForm.userId ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="120px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="dataForm.username" placeholder="登录帐号"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password" :class="{ 'is-required': !dataForm.userId }">
        <el-input v-model="dataForm.password" type="password" placeholder="密码"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="comfirmPassword" :class="{ 'is-required': !dataForm.userId }">
        <el-input v-model="dataForm.comfirmPassword" type="password" placeholder="确认密码"></el-input>
      </el-form-item>
      <el-form-item label="中文名" prop="ipName">
        <el-input v-model="dataForm.ipName" placeholder="中文名"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="dataForm.mobile" placeholder="手机号"></el-input>
      </el-form-item>
      <el-form-item label="角色" size="mini" prop="roleIdList">
        <el-checkbox-group v-model="dataForm.roleIdList">
          <el-checkbox v-for="role in roleList" :key="role.roleId" :label="role.roleId">{{ role.remark }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="状态" size="mini" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="0">禁用</el-radio>
          <el-radio :label="1">正常</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import { isEmail, isMobile } from '@/utils/validate'
  import * as $http from '@/api/sys/user'
  import * as $httpRole from '@/api/sys/role'
  export default {
    data () {
      var validatePassword = (rule, value, callback) => {
        if (!this.dataForm.userId && !/\S/.test(value)) {
          callback(new Error('密码不能为空'))
        } else {
          callback()
        }
      }
      var validateComfirmPassword = (rule, value, callback) => {
        if (!this.dataForm.userId && !/\S/.test(value)) {
          callback(new Error('确认密码不能为空'))
        } else if (this.dataForm.password !== value) {
          callback(new Error('确认密码与密码输入不一致'))
        } else {
          callback()
        }
      }

      var validateMobile = (rule, value, callback) => {
        if (!isMobile(value)) {
          callback(new Error('手机号格式错误'))
        } else {
          callback()
        }
      }
      return {
        visible: false,
        roleList: [],
        dataForm: {
          userId: 0,
          username: '',
          password: '',
          comfirmPassword: '',
          salt: '',
          ipName: '',
          mobile: '',
          roleIdList: [],
          status: 1
        },
        dataRule: {
          username: [
            { required: true, message: '用户名不能为空', trigger: 'blur' }
          ],
          password: [
            { validator: validatePassword, trigger: 'blur' }
          ],
          comfirmPassword: [
            { validator: validateComfirmPassword, trigger: 'blur' }
          ],

//          mobile: [
//            { required: true, message: '手机号不能为空', trigger: 'blur' },
//            { validator: validateMobile, trigger: 'blur' }
//          ]
        }
      }
    },
    methods: {
      init (id) {
        this.dataForm.userId = id || 0
        let _this = this,
            postData = Object.assign({},this.dataForm)
        $httpRole.getSelectRole().then(response => {
          _this.roleList = response && response.code === 0 ? response.list : []
        }).then(() => {
          _this.visible = true
          _this.$nextTick(() => {
            _this.$refs['dataForm'].resetFields()
          })
        }).then(() => {
          if (this.dataForm.userId) {
            $http.getUserInfo(this.dataForm.userId).then(response => {
              if (response && response.code === 0) {
                _this.dataForm.username = response.user.username
                _this.dataForm.salt = response.user.salt
                _this.dataForm.ipName = response.user.ipName
                _this.dataForm.mobile = response.user.mobile
                _this.dataForm.roleIdList = response.user.roleIdList
                _this.dataForm.status = response.user.status
              }
            })
          }
        });
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            let postData = Object.assign({},this.dataForm);
            postData.userId = this.dataForm.userId || undefined;
            delete postData.id;
            delete postData.comfirmPassword;
            $http[`${this.dataForm.userId ? 'updUser' : 'addUser'}`](postData).then((data) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })

          }
        })
      }
    }
  }
</script>
